package com.kb.erp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.db.sql.Wrapper;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kb.erp.entity.DesignOrder;
import com.kb.erp.entity.PcbaOrder;
import com.kb.erp.excel.PcbaData;
import com.kb.erp.mapper.pg.DesignOrderMapper;
import com.kb.erp.mapper.sqlServer.PcbaOrderMapper;
import com.kb.erp.service.CadOrderService;
import com.kb.erp.service.DesignOrderService;
import com.kb.erp.service.PcbaOrderService;
import com.kb.erp.util.CopyShareFileUtil;
import com.kb.erp.util.MessageUtil;
import com.xxl.job.core.context.XxlJobHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.nio.charset.Charset;
import java.sql.Date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * (PcbaOrder)表服务实现类
 *
 * @author makejava
 * @since 2023-11-24 09:37:14
 */
@Service("pcbaOrderService")
@DS("slave-1")
@Slf4j
public class PcbaOrderServiceImpl implements PcbaOrderService {

    @Value("${shared.account:szkb\\17447}")
    private String account;

    @Value("${shared.password:17447#$%}")
    private String password;
    @Value("${shared.url:smb://192.168.81.7/order}")
    private String url;

    @Resource
    private PcbaOrderMapper pcbaOrderMapper;
    @Resource
    private DesignOrderMapper designOrderMapper;
    @Resource
    private DesignOrderService designOrderService;
    @Resource
    private CadOrderService cadOrderService;


    public boolean selectData(Integer date) {
        log.info("设计协同数据同步启动成功：{}", DateUtil.now());
        XxlJobHelper.log("设计协同数据同步启动成功：" + DateUtil.now());
        try {
            long startTime = System.currentTimeMillis();
//        LambdaQueryWrapper<PcbaOrder> queryWrapper = new LambdaQueryWrapper<>();
//        //查询设计部门的订单
//        queryWrapper.eq(PcbaOrder::getGc,"设计");
            PcbaOrder order = new PcbaOrder();
            order.setGc("设计");
            order.setStatus("有效");
            Calendar calendar = Calendar.getInstance();
            // 获取前1天的日期
            if (Objects.isNull(date)) {
                //date取反数
                calendar.add(Calendar.DATE, -1);
            } else {
                calendar.add(Calendar.DATE, -date);
            }
            order.setOrderdate(calendar.getTime());
            List<PcbaOrder> pcbaOrderList = pcbaOrderMapper.selectByGc(order);
            if (CollectionUtils.isEmpty(pcbaOrderList)) {
                log.info("符合的数据为空：" + DateUtil.now());
                XxlJobHelper.log("符合的数据为空：" + DateUtil.now());
                return true;
            }
            List<DesignOrder> designOrderList = new ArrayList<>();
            for (PcbaOrder pcbaOrder : pcbaOrderList) {
                DesignOrder designOrder = new DesignOrder();
                BeanUtils.copyProperties(pcbaOrder, designOrder);
                //订单时间拼接 todo
//                designOrder.setOrderDate();
                String invType = pcbaOrder.getInvType();
                if (invType != null) {
                    if (invType.contains("%")) {
                        //去除%号
                        invType = invType.substring(0, invType.length() - 1);
                        designOrder.setInvType(invType.trim());
                    }
                    designOrder.setInvType(invType.trim());
                } else {
                    designOrder.setInvType("0");
                }
                designOrder.setId(pcbaOrder.getAutoid()).setCreateTime(LocalDateTime.now()).setUpdateTime(LocalDateTime.now())
                        .setOrderDate(pcbaOrder.getOrderdate()).setDeliveryDate(pcbaOrder.getDeliverydate()).setOrderNo(pcbaOrder.getOrderno())
                        .setContractNo(pcbaOrder.getContractno()).setUnitPrice(pcbaOrder.getUnitprice())
                        .setTotalAmount(pcbaOrder.getZje()).setVersion(1L).setCreateBy("admin").setUpdateBy("admin")
                        .setUnitQuantity(pcbaOrder.getUnitquantity()).setPinAmount(pcbaOrder.getSetquantity())
                        .setDept1(pcbaOrder.getDept1().trim()).setDept2(pcbaOrder.getDept2().trim()).setDept3(pcbaOrder.getDept3().trim())
                        .setCustomerCode(pcbaOrder.getCustomerCode().trim()).setId(null);

                designOrderList.add(designOrder);
            }
            //先查询不存在 再插入
            for (DesignOrder designOrder : designOrderList) {
                List<DesignOrder> designOrders = designOrderService.queryList(designOrder);
                if (CollectionUtils.isEmpty(designOrders)){
                    designOrderService.save(designOrder);
                }
            }
            log.info(DateUtil.now() + "设计部门订单插入耗时：" + (System.currentTimeMillis() - startTime));
            XxlJobHelper.log("数据同步成功：" + DateUtil.now());
        } catch (Exception e) {
            MessageUtil.sentMessageToAssistant("23988", "设计部门订单插入失败：" + e.getMessage());
            XxlJobHelper.log(LocalDateTime.now() + "-->数据更新失败-->" + e.getMessage());
            throw new RuntimeException(e);
        }
        return true;
    }

    @Override
    public boolean ERP2Cad(Integer date) {
        log.info("开始同步订单信息到cad：{}", DateUtil.now());
        XxlJobHelper.log("开始同步订单信息到cad：" + DateUtil.now());
        try {
            PcbaOrder order = new PcbaOrder();
            order.setGc("设计");
            order.setStatus("有效");
            Calendar calendar = Calendar.getInstance();
            // 获取前1天的日期
            if (Objects.isNull(date)) {
                //date取反数
                calendar.add(Calendar.DATE, -1);
            } else {
                calendar.add(Calendar.DATE, -date);
            }
            //时间参数是前一天
            order.setOrderdate(calendar.getTime());
            order.setGc("设计");

            // 时间参数是年
//            LocalDate today = LocalDate.now();
//            LocalDate firstDayOfYear = today.with(TemporalAdjusters.firstDayOfYear());
//            order.setOrderdate(Date.valueOf(firstDayOfYear))

            ;
            List<PcbaData> pcbaOrderList = pcbaOrderMapper.selectByGcExcel(order);

            if (CollectionUtils.isEmpty(pcbaOrderList)) {
                log.info("符合的数据为空：" + DateUtil.now());
                XxlJobHelper.log("符合的数据为空：" + DateUtil.now());
                return true;
            }
            //先查询不存在 再插入
            for (PcbaData designOrder : pcbaOrderList) {
                List<PcbaData> designOrders = cadOrderService.queryListByOrderNo(designOrder.getOrderNo());
                if (CollectionUtils.isEmpty(designOrders)){
                    cadOrderService.save(designOrder);
                }else {
                    designOrder.setId(designOrders.get(0).getId());
                    cadOrderService.updateById(designOrder);
                }
            }
            XxlJobHelper.log("数据同步成功：" + DateUtil.now());
        } catch (Exception e) {
            MessageUtil.sentMessageToAssistant("23988", "订单数据同步到cad失败：" + e.getMessage());
            XxlJobHelper.log(LocalDateTime.now() + "-->订单数据同步到cad失败-->" + e.getMessage());
            throw new RuntimeException(e);
        }
        return true;
    }

    @Override
    public void searchOrder() {

        try {
            log.info("设计协同数据同步到共享Excel开始：" + DateUtil.now());
            XxlJobHelper.log("设计协同数据同步到共享Excel成功：" + DateUtil.now());
            LocalDate today = LocalDate.now();
            int year = today.getYear();
            // 获取JAR包所在目录的路径
            File file = new File("");
            String filePath = file.getCanonicalPath();
            String fileNameBJ = filePath + "/file/" + year + "_bj.csv";
            String fileNameSZ = filePath + "/file/" + year + "_sz.csv";

            PcbaOrder order = new PcbaOrder();
            order.setGc("设计");

            // 获取当年的第一天
            LocalDate firstDayOfYear = today.with(TemporalAdjusters.firstDayOfYear());
            order.setOrderdate(Date.valueOf(firstDayOfYear));
            List<PcbaData> pcbaOrderList = pcbaOrderMapper.selectByGcExcel(order);
            if (CollectionUtils.isEmpty(pcbaOrderList)) {
                log.info("符合的数据为空：{}", DateUtil.now());
                XxlJobHelper.log("符合的数据为空：" + DateUtil.now());
                return;
            }
/*            //最近1天  旧逻辑 获取最近一天 累加
            // 获取当前日期
            Calendar calendar = Calendar.getInstance();
            // 获取前1天的日期
            calendar.add(Calendar.DATE, -1);
            order.setOrderdate(calendar.getTime());
            List<PcbaData> pcbaOrderList = pcbaOrderMapper.selectByGcExcel(order);
            if (CollectionUtils.isEmpty(pcbaOrderList)) {
                log.info("符合的数据为空：" + DateUtil.now());
                XxlJobHelper.log("符合的数据为空：" + DateUtil.now());
                return;
            }
            // 获取JAR包所在目录的路径
            File file = new File("");
            String filePath = file.getCanonicalPath();
//            String fileName = filePath+"/file/2024.csv";
            String fileNameBJ = filePath+"/file/bj.csv";
            String fileNameSZ = filePath+"/file/sz.csv";
            //获取表格原有数据
            List<PcbaData> oldListBJ = null;
            List<PcbaData> oldListSZ = null;
            try {
                oldListBJ = EasyExcel.read(fileNameBJ).charset(Charset.forName("GBK")).head(PcbaData.class).sheet().doReadSync();
                oldListSZ = EasyExcel.read(fileNameSZ).charset(Charset.forName("GBK")).head(PcbaData.class).sheet().doReadSync();
            } catch (Exception e) {
                XxlJobHelper.log("数据读取异常：" + e.getMessage());
            }
            //合并list
            if (!CollectionUtils.isEmpty(oldListBJ)){
                pcbaOrderList.addAll(oldListBJ);
            }
            if (!CollectionUtils.isEmpty(oldListSZ)){
                pcbaOrderList.addAll(oldListSZ);
            }
//            去重
            List<PcbaData> pcbaDataList = pcbaOrderList.stream().
                    filter(distinctByKey(PcbaData::getOrderNo))
                    .collect(Collectors.toList());*/

            //根据产能组织拆分 北京-->bj.csv  其他-->sz.csv
//             对列表中每个元素的字符串字段去除空格
            List<PcbaData> trimmedList = pcbaOrderList.stream()
                    .peek(PcbaData::trimFields)
                    //去除回车符 remark
                    .peek(e -> e.setRemark(e.getRemark().replaceAll("\\s", "")))
                    .toList();
//            List<PcbaData> bjList = trimmedList.stream().filter(e -> Objects.equals(e.getProdOrg(), "北京")).collect(Collectors.toList());
//            List<PcbaData> szList = trimmedList.stream().filter(e -> !Objects.equals(e.getProdOrg(), "北京")).collect(Collectors.toList());


            //加入天津
            List<PcbaData> bjList = trimmedList.stream()
                    .filter(e -> "北京".equals(e.getProdOrg()) || "天津".equals(e.getProdOrg()))
                    .collect(Collectors.toList());

            List<PcbaData> szList = trimmedList.stream()
                    .filter(e -> !"北京".equals(e.getProdOrg()) && !"天津".equals(e.getProdOrg()))
                    .collect(Collectors.toList());


            if (!CollectionUtils.isEmpty(bjList)) {
                EasyExcel.write(fileNameBJ, PcbaData.class).excelType(ExcelTypeEnum.CSV).charset(Charset.forName("GBK")).sheet("ORDERS").doWrite(bjList);
                //        这里要注意，remoteUrl参数（也就是第一个参数），必须是有smb://前缀的，这是协议！后面拼接ip地址，再拼接的就是第一步中，共享文件夹的共享名！
                CopyShareFileUtil.copyToWindowsShare(fileNameBJ, url, account, password);
            }
            if (!CollectionUtils.isEmpty(szList)) {
                EasyExcel.write(fileNameSZ, PcbaData.class).excelType(ExcelTypeEnum.CSV).charset(Charset.forName("GBK")).sheet("ORDERS").doWrite(szList);
                //        这里要注意，remoteUrl参数（也就是第一个参数），必须是有smb://前缀的，这是协议！后面拼接ip地址，再拼接的就是第一步中，共享文件夹的共享名！
                CopyShareFileUtil.copyToWindowsShare(fileNameSZ, url, account, password);
            }

        } catch (Exception e) {
            MessageUtil.sentMessageToAssistant("23988", "设计数据共享到文件夹失败：" + e.getMessage());
            XxlJobHelper.log(LocalDateTime.now() + "-->设计数据共享到文件夹失败-->" + e.getMessage());
            throw new RuntimeException(e);
        }
    }

    // 根据指定的 key 提取元素，并通过 HashSet 的 add 方法判断是否重复
    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Set<Object> seen = new HashSet<>();
        return t -> seen.add(keyExtractor.apply(t));
    }
}
